<?php

class Articles extends CI_Controller{

	var $data;

	function __construct(){
		parent::__construct();
		$this->load->model('articles_model');
		$this->load->model('menu_model');
		$this->data['menuitems'] = $this->menu_model->menuitems;
		$this->data['isLoggedIn'] = $this->user_model->isLoggedIn();
	}

	// Display all articles
	function index(){
		
		$this->load->library('pagination');
		
		$config['base_url'] = site_url().'/articles/index/';
		$config['total_rows'] = $this->articles_model->getNumberOfArticles();
		$config['per_page'] = '5';
		$config['uri_segment'] = '3';
		
		$this->pagination->initialize($config);
		
		$this->data['page_links'] = $this->pagination->create_links();
		
		
		if($query = $this->articles_model->getLimitOfArticles($config['per_page'],  $this->uri->segment(3)))
		{
			$this->data['articles'] = $query;
		}

		$this->data['main_content'] =  'articles_view';
		$this->data['selected_item'] = $this->menu_model->getMenuItem('articles');
		$this->load->view('includes/template', $this->data);

	}

	// Handle the page for creating a new article
	function writeNewArticle(){
		if($this->data['isLoggedIn']==true){
			$this->load->helper('form');

			$this->data['title'] = '';
			$this->data['text'] = '';
			$this->data['categories'] = $this->articles_model->getCategories();

			$this->data['main_content'] =  'new_article_view';
			$this->data['selected_item'] = $this->menu_model->getMenuItem('articles');
			$this->load->view('includes/template', $this->data);
		}
		else redirect(site_url().'/articles/');
	}

	// Handle the creation of a new article (after the form is filled out/"Submit" is clicked)
	function newArticle(){
		if($this->data['isLoggedIn']==true){
			$this->load->library('form_validation');
			$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
			$this->form_validation->set_rules('text', 'Text', 'required|xss_clean');
			if($this->form_validation->run() == FALSE){

				$this->data['title'] = $this->input->post('title');
				$this->data['text'] = $this->input->post('text');
				$this->data['categories'] = $this->articles_model->getCategories();

				$this->data['main_content'] =  'new_article_view';
				$this->data['selected_item'] = $this->menu_model->getMenuItem('articles');
				$this->load->view('includes/template', $this->data);
			} else {
				//$data;
				$data = array(
					'title' => $this->input->post('title'),
					'text' => $this->input->post('text'),
					'category' => $this->input->post('category'),
				);

				$this->articles_model->insertArticle($data);

				$this->load->model('email_model');
				$this->email_model->sendEmails($this->user_model->getUserIdFromSession());
				redirect(site_url().'/articles/');
			}
		}
		else redirect(site_url().'/articles/');
	}

	// Handle a single article page
	function id(){
		$this->load->helper('add_this_helper');
		$articleid = $this->uri->segment(3);
		$commentsQuery = $this->articles_model->getComments($articleid);

		$comments = array();
		foreach($commentsQuery as $comment){
			$tmp = array('author'=>$this->user_model->getUsername($comment->userID), 'date'=>$comment->date, 'text'=>$comment->text);
			array_push($comments, $tmp);

		}

		$this->data['article'] = $this->articles_model->getArticle($articleid);
		$this->data['articleID'] = $articleid;
		$this->data['comments'] = $comments;
		$this->data['bookmarked'] = $this->articles_model->isBookmarked($this->user_model->getUserIdFromSession(), $articleid);
		$this->data['subscribed'] = $this->articles_model->isSubscribing($this->user_model->getUserIdFromSession(), $this->data['article']->userID);
		$this->data['ratingAvg'] = $this->data['article']->ratingAvg;
		
		$this->data['main_content'] =  'article_view';
		$this->data['selected_item'] = $this->menu_model->getMenuItem('articles');
		$this->load->view('includes/template', $this->data);
	}

	// Display all articles of a certain category
	function categories(){
		
		$categoryid = $this->articles_model->getCategoryID($this->uri->segment(3));
		
		$this->load->library('pagination');
		
		$config['base_url'] = site_url().'/articles/categories/'.$this->uri->segment(3);
		$config['total_rows'] = $this->articles_model->getNumberOfArticlesInCategory($categoryid);
		$config['per_page'] = '5';
		$config['uri_segment'] = '4';
		
		$this->pagination->initialize($config);
		
		$this->data['page_links'] = $this->pagination->create_links();
		
		
		if($query = $this->articles_model->getLimitOfArticlesInCategory($categoryid, $config['per_page'],  $this->uri->segment(4)))
		{
			$this->data['articles'] = $query;
		}

		$this->data['main_content'] =  'articles_view';
		$this->data['selected_item'] = $this->menu_model->getMenuItem('articles');
		$this->data['category'] = ucwords($this->uri->segment(3));
		$this->load->view('includes/template', $this->data);
	}

	// Handle the request to write a new comment
	function newComment(){
		if($this->data['isLoggedIn']==true){
			$this->load->model('user_model');
			$data = array(
				'articleID' => $this->input->post('articleID'),
				'userID' => $this->user_model->getUserIdFromSession(),
				'text' => $this->input->post('text'),
			);
			$this->articles_model->insertComment($data);
			redirect(site_url().'/articles/id/'.$this->input->post('articleID'));
		} else
		redirect(site_url().'/articles/');
	}

	//Bookmarks an article
	function bookmarkArticle(){
		$articleid = $this->input->post('articleid');
		$userid = $this->input->post('userid');
		$this->articles_model->bookmarkArticle($userid, $articleid);
	}

	//Unbookmarks an article
	function unbookmarkArticle(){
		if($this->input->is_ajax_request()){
			$articleid = $this->input->post('articleid');
			$userid = $this->input->post('userid');
			$this->articles_model->unbookmarkArticle($userid, $articleid);
		}
		else{
			$data = $this->uri->uri_to_assoc(3);
			$this->articles_model->unbookmarkArticle($data['userid'], $data['authorid']);
			redirect(site_url()."/user/profile/userid/".$data['userid']);
		}

	}

	// Handle the deletion of the article specified with the uri
	function delete(){
		if($this->data['isLoggedIn']==true){
			//$this->load->model('user_model'); no need since we load it in autoload
			$author = $this->articles_model->getUserIDByArticleID($this->uri->segment(3));
			if($this->user_model->sessionUser($author->userID)==TRUE){
				$this->articles_model->deleteArticle($this->uri->segment(3));
			}
			redirect(site_url().'/user/profile/userid/'.$this->user_model->getUserIdFromSession());
		} else
		redirect(site_url().'/articles/');
	}

	//Subscribe to an author
	function subscribe(){
		$userid = $this->input->post('userid');
		$authorid = $this->input->post('authorid');
		$this->articles_model->subscribe($userid, $authorid);
	}

function unsubscribe(){
		$data = $this->uri->uri_to_assoc(3);
		$this->articles_model->unsubscribe($data['userid'], $data['authorid']);
		redirect(site_url()."/user/profile/userid/".$data['userid']);
	}

	//Edit an article that is specified within the uri
	function edit(){
		$articleid = $this->uri->segment(3);
		$article = $this->articles_model->getArticle($articleid);
		$authorid = $article->userID;
		if(($this->data['isLoggedIn']==TRUE) && ($this->user_model->sessionUser($authorid)==TRUE)){

			$this->data['articleid'] = $article->articleID;
			$this->data['title'] = $article->title;
			$this->data['text'] = $article->text;
			$this->data['img'] = $article->imgRaw.$article->imgExt;
			$this->data['img_thumb'] = $article->imgRaw.'_thumb'.$article->imgExt;
			$this->data['current_categoryID'] = $article->categoryID;
			//$this->data['article'] = $article;
			$this->data['categories'] = $this->articles_model->getCategories();

			$this->data['main_content'] =  'edit_article_view';
			$this->data['selected_item'] = $this->menu_model->getMenuItem('articles');
			$this->load->view('includes/template', $this->data);

		}
		else{
			redirect(site_url(), '/articles/');
		}
	}

	//Updates an article
	function updateArticle(){
		if($this->data['isLoggedIn']==true){
			$this->load->library('form_validation');
			$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
			$this->form_validation->set_rules('text', 'Text', 'required|xss_clean');
			if($this->form_validation->run() == FALSE){

				$this->data['articlid'] = $this->input->post('articleid');
				$this->data['title'] = $this->input->post('title');
				$this->data['text'] = $this->input->post('text');
				$this->data['img'] = $article->imgRaw.$article->imgExt;
				$this->data['img_thumb'] = $article->imgRaw.'_thumb'.$article->imgExt;
				$this->data['current_categoryID'] = $this->input->post('category');

				$this->data['categories'] = $this->articles_model->getCategories();

				$this->data['main_content'] =  'edit_article_view';
				$this->data['selected_item'] = $this->menu_model->getMenuItem('articles');
				$this->load->view('includes/template', $this->data);
			} else {
				//$data;
				$data = array(
					'articleid' => $this->input->post('articleid'),
					'title' => $this->input->post('title'),
					'text' => $this->input->post('text'),
					'category' => $this->input->post('category'),
				);

				$this->articles_model->updateArticle($data['articleid'],$data['title'], $data['text'], $data['category']);
				redirect(site_url().'/articles/');
			}
		}
		else redirect(site_url().'/articles/');
	}

	

	function submitRating(){
		
		// This was sent by JS, the articleID and the rating.
            $rating = (int)$_POST['rating'];
            $articleID = (int)$_POST['id'];
            $this->articles_model->updateRating($articleID, $rating);
            $article = $this->articles_model->getArticle($articleID);
            $ratingAvg = $article->ratingAvg;

                //Show stars again, but this time, dont allow vote

                          ?>
		<div class="floatleft">
			<div id="star_container_<?php echo $articleID; ?>">
				<div id="rated_<?php echo $articleID; ?>">
					<span class="rated_star_1"><img src="<?php echo base_url() ?>images/star_blank.png" alt="" <?php if($ratingAvg > 0) { echo"class='hover_star_rated'"; } ?> /></span>
					<span class="rated_star_2"><img src="<?php echo base_url() ?>images/star_blank.png" alt="" <?php if($ratingAvg > 1.5) { echo"class='hover_star_rated'"; } ?> /></span>
					<span class="rated_star_3"><img src="<?php echo base_url() ?>images/star_blank.png" alt="" <?php if($ratingAvg > 2.5) { echo"class='hover_star_rated'"; } ?> /></span>
					<span class="rated_star_4"><img src="<?php echo base_url() ?>images/star_blank.png" alt="" <?php if($ratingAvg > 3.5) { echo"class='hover_star_rated'"; } ?> /></span>
					<span class="rated_star_5"><img src="<?php echo base_url() ?>images/star_blank.png" alt="" <?php if($ratingAvg > 4.5) { echo"class='hover_star_rated'"; } ?> /></span>
					<?php echo "Average: ".round($ratingAvg, 2); ?>
				</div>
			</div>
		</div>
		<div class="starl_rating">
			Your rating: <strong><?php echo $rating; ?></strong> Star(s)
			
		</div>				
		<?php

			
	}

}
